<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { openPaymentModal, checkAccessPermission } from '../utils/paymentUtils.js'

const router = useRouter()

// 模拟用户登录状态和会员等级
const userInfo = ref({
  username: '',
  level: '游客', // 游客、学子会员、传人会员、大师会员
  isLoggedIn: false
})

// 获取Vue应用实例，用于调用全局方法
const app = getCurrentInstance()

// 模拟传统剧目数据
const traditionalPlays = [
  {
    id: 1,
    title: '大闹天宫',
    cover: 'https://picsum.photos/id/130/400/500',
    description: '根据中国古典小说《西游记》改编，讲述孙悟空大闹天宫的精彩故事。',
    duration: '85分钟',
    year: '1961',
    characters: [
      { name: '孙悟空', description: '齐天大圣，本领高强' },
      { name: '玉皇大帝', description: '天庭之主' },
      { name: '二郎神', description: '天界战神' }
    ],
    previewUrl: 'https://picsum.photos/id/131/1200/675',
    videoUrl: '#',
    tags: ['神话', '经典', '动作']
  },
  {
    id: 2,
    title: '白蛇传',
    cover: 'https://picsum.photos/id/132/400/500',
    description: '讲述白蛇白素贞与许仙的爱情故事，感人至深。',
    duration: '90分钟',
    year: '1958',
    characters: [
      { name: '白素贞', description: '千年白蛇精，温柔善良' },
      { name: '许仙', description: '憨厚老实的医生' },
      { name: '小青', description: '白素贞的妹妹，青蛇精' }
    ],
    previewUrl: 'https://picsum.photos/id/133/1200/675',
    videoUrl: '#',
    tags: ['爱情', '神话', '悲剧']
  },
  {
    id: 3,
    title: '杨家将',
    cover: 'https://picsum.photos/id/134/400/500',
    description: '讲述北宋杨家将满门忠烈，保家卫国的英雄事迹。',
    duration: '120分钟',
    year: '1965',
    characters: [
      { name: '杨继业', description: '杨家老令公' },
      { name: '佘太君', description: '杨家主母，深明大义' },
      { name: '杨六郎', description: '杨家七子之一，英勇善战' }
    ],
    previewUrl: 'https://picsum.photos/id/135/1200/675',
    videoUrl: '#',
    tags: ['历史', '战争', '忠义']
  }
]

// 加载用户信息
onMounted(() => {
  const loginStatus = localStorage.getItem('isLoggedIn') === 'true'
  userInfo.value.isLoggedIn = loginStatus
  
  if (loginStatus) {
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      const parsed = JSON.parse(storedUserInfo)
      userInfo.value.username = parsed.username || parsed.phone || ''
      userInfo.value.level = parsed.level || '普通会员'
    }
  }
})

// 计算用户权限
const userPermissions = computed(() => {
  switch (userInfo.value.level) {
    case '学子会员':
      return {
        canWatch480p: true,
        canWatch1080p: false,
        canWatch4K: false,
        hasBasicAnalysis: true,
        hasDetailedAnalysis: false,
        hasMasterCommentary: false,
        monthlyFreePlays: 2,
        unlimitedPlayback: false,
        hasBehindScenes: false,
        canDownloadScripts: false,
        hasOfflinePriority: false
      }
    case '传人会员':
      return {
        canWatch480p: true,
        canWatch1080p: true,
        canWatch4K: false,
        hasBasicAnalysis: true,
        hasDetailedAnalysis: true,
        hasMasterCommentary: false,
        monthlyFreePlays: 999,
        unlimitedPlayback: true,
        hasBehindScenes: true,
        canDownloadScripts: false,
        hasOfflinePriority: false
      }
    case '大师会员':
      return {
        canWatch480p: true,
        canWatch1080p: true,
        canWatch4K: true,
        hasBasicAnalysis: true,
        hasDetailedAnalysis: true,
        hasMasterCommentary: true,
        monthlyFreePlays: 999,
        unlimitedPlayback: true,
        hasBehindScenes: true,
        canDownloadScripts: true,
        hasOfflinePriority: true
      }
    default:
      return {
        canWatch480p: false,
        canWatch1080p: false,
        canWatch4K: false,
        hasBasicAnalysis: false,
        hasDetailedAnalysis: false,
        hasMasterCommentary: false,
        monthlyFreePlays: 0,
        unlimitedPlayback: false,
        hasBehindScenes: false,
        canDownloadScripts: false,
        hasOfflinePriority: false
      }
  }
})

// 判断用户是否可以观看特定剧目
const canUserWatchPlay = (play) => {
  if (!userInfo.value.isLoggedIn) {
    return false
  }
  
  // 使用支付工具函数检查权限
  return checkAccessPermission(play.accessLevel || userInfo.value.level)
}

// 处理观看按钮点击
const handleWatch = (play) => {
  if (!userInfo.value.isLoggedIn) {
    router.push('/login')
    return
  }
  
  // 根据用户等级和剧目的观看权限判断
  const canWatch = canUserWatchPlay(play)
  
  if (canWatch || userPermissions.value.unlimitedPlayback || userPermissions.value.monthlyFreePlays > 0) {
    // 这里可以跳转到剧目详情或播放页面
    alert(`即将播放《${play.title}》`)
  } else {
    // 如果是需要购买单个剧目的情况
    if (play.purchaseOption && play.price > 0) {
      if (confirm(`是否购买此剧目单独观看权限？价格：¥${play.price}`)) {
        openPaymentModal(app?.proxy, {
          id: play.id,
          name: play.title,
          price: play.price,
          type: 'single_play',
          details: play.description
        })
      }
    } else {
      // 提示升级会员
      if (confirm(`您的会员等级不足以观看此内容，是否升级会员？`)) {
        router.push('/membership')
      }
    }
  }
}

// 处理会员升级
const upgradeMembership = () => {
  if (!userInfo.value.isLoggedIn) {
    router.push('/login')
    return
  }
  
  // 跳转到会员中心页面
  router.push('/membership')
}
</script>

<template>
  <div class="traditional-plays-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">传统剧目</h1>
      <p class="page-subtitle">经典传承，光影永恒</p>
    </div>

    <!-- 会员提示横幅 -->
    <div class="membership-banner">
      <div class="container">
        <div class="banner-content">
          <div class="banner-text">
            <h3>🎭 会员专享特权</h3>
            <p v-if="userInfo.isLoggedIn">
              您当前是 <span class="user-level">{{ userInfo.level }}</span>，
              <template v-if="userPermissions.unlimitedPlayback">
                可享受无限制高清观看特权！
              </template>
              <template v-else-if="userPermissions.monthlyFreePlays > 0">
                本月还剩 {{ userPermissions.monthlyFreePlays }} 部免费观看额度。
              </template>
              <template v-else>
                免费额度已用完，请升级会员继续观看。
              </template>
            </p>
            <p v-else>
              登录后可免费试看2分钟精彩片段，升级会员享受完整观看体验！
            </p>
          </div>
          <div class="banner-actions">
            <button v-if="!userInfo.isLoggedIn" class="btn btn-primary" @click="router.push('/login')">
              立即登录
            </button>
            <button v-else-if="userInfo.level === '游客' || userInfo.level === '普通会员'" 
                    class="btn btn-primary" @click="upgradeMembership">
              升级会员
            </button>
            <button v-else class="btn btn-outline">
              会员中心
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 剧目分类筛选 -->
    <div class="filter-section container">
      <div class="filter-tabs">
        <button class="filter-tab active">全部剧目</button>
        <button class="filter-tab">神话传说</button>
        <button class="filter-tab">历史故事</button>
        <button class="filter-tab">民间故事</button>
        <button class="filter-tab">经典名著</button>
      </div>
      <div class="sort-options">
        <label>排序方式：</label>
        <select>
          <option>最新上线</option>
          <option>人气推荐</option>
          <option>年份最早</option>
          <option>年份最新</option>
        </select>
      </div>
    </div>

    <!-- 剧目列表 -->
    <div class="plays-section container">
      <div class="plays-grid">
        <div v-for="play in traditionalPlays" :key="play.id" class="play-card">
          <!-- 剧目封面 -->
          <div class="play-cover">
            <img :src="play.cover" :alt="play.title" class="cover-image" />
            <!-- 会员标识 -->
            <div class="membership-badge" v-if="!userPermissions.canWatch480p">
              <span class="badge-text">会员专享</span>
            </div>
            <!-- 观看按钮 -->
            <button class="play-button" @click="handleWatch(play)">
              <span class="play-icon">▶</span>
              <span class="play-text">
                {{ userPermissions.unlimitedPlayback || userPermissions.monthlyFreePlays > 0 ? '立即观看' : '试看2分钟' }}
              </span>
            </button>
          </div>
          <!-- 剧目信息 -->
          <div class="play-info">
            <h3 class="play-title">{{ play.title }}</h3>
            <div class="play-meta">
              <span class="play-year">{{ play.year }}</span>
              <span class="play-duration">{{ play.duration }}</span>
            </div>
            <p class="play-description">{{ play.description }}</p>
            <div class="play-tags">
              <span v-for="(tag, index) in play.tags" :key="index" class="tag">{{ tag }}</span>
            </div>
            <!-- 权限提示 -->
            <div class="permission-tips">
              <div v-if="userPermissions.canWatch480p" class="permission-item">
                <span class="permission-icon">✅</span>
                <span>480P完整观看</span>
              </div>
              <div v-if="userPermissions.canWatch1080p" class="permission-item">
                <span class="permission-icon">✅</span>
                <span>1080P高清画质</span>
              </div>
              <div v-if="userPermissions.canWatch4K" class="permission-item">
                <span class="permission-icon">✅</span>
                <span>4K超清画质</span>
              </div>
              <div v-if="userPermissions.hasMasterCommentary" class="permission-item">
                <span class="permission-icon">✅</span>
                <span>大师解说版</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more">
        <button class="btn btn-outline">加载更多</button>
      </div>
    </div>

    <!-- 会员推广卡片 -->
    <div class="promotion-section container">
      <div class="promotion-card">
        <div class="promotion-image">
          <img src="https://picsum.photos/id/136/600/400" alt="会员专享" class="promo-image" />
        </div>
        <div class="promotion-content">
          <h3 class="promotion-title">升级会员，畅享全部内容</h3>
          <ul class="promotion-benefits">
            <li>🎬 4K超清画质，极致观影体验</li>
            <li>📚 独家幕后花絮，制作解析</li>
            <li>👨‍🏫 大师解说版，深度理解作品</li>
            <li>🎨 创作手稿下载，艺术收藏</li>
            <li>🎫 线下活动优先权，亲密接触艺术家</li>
          </ul>
          <button class="btn btn-primary" @click="upgradeMembership">
            立即升级，首月仅¥9.9
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 页面容器 */
.traditional-plays-container {
  min-height: 100vh;
  background-color: var(--color-background);
}

/* 页面头部 */
.page-header {
  background-color: var(--color-primary);
  color: white;
  padding: 3rem 0;
  text-align: center;
}

.page-title {
  font-size: 2.5rem;
  margin: 0 0 0.5rem 0;
  font-weight: bold;
}

.page-subtitle {
  font-size: 1.2rem;
  margin: 0;
  opacity: 0.9;
}

/* 会员提示横幅 */
.membership-banner {
  background-color: var(--color-background-soft);
  border-bottom: 1px solid var(--color-border);
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 0;
}

.banner-text h3 {
  margin: 0 0 0.5rem 0;
  color: var(--color-secondary);
}

.banner-text p {
  margin: 0;
  color: var(--color-text);
}

.user-level {
  font-weight: bold;
  color: var(--color-primary);
}

.banner-actions {
  display: flex;
  gap: 1rem;
}

/* 筛选部分 */
.filter-section {
  padding: 2rem 0;
  border-bottom: 1px solid var(--color-border);
}

.filter-tabs {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  overflow-x: auto;
  padding-bottom: 0.5rem;
}

.filter-tab {
  padding: 0.5rem 1.5rem;
  background-color: var(--color-background-soft);
  border: 1px solid var(--color-border);
  border-radius: 2rem;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.filter-tab:hover {
  background-color: var(--color-primary-light);
}

.filter-tab.active {
  background-color: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.sort-options select {
  padding: 0.5rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background-color: white;
}

/* 剧目列表 */
.plays-section {
  padding: 3rem 0;
}

.plays-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

.play-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.play-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

/* 剧目封面 */
.play-cover {
  position: relative;
  height: 220px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.play-card:hover .cover-image {
  transform: scale(1.05);
}

.membership-badge {
  position: absolute;
  top: 1rem;
  right: 1rem;
  background-color: rgba(255, 87, 34, 0.9);
  color: white;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
  font-size: 0.9rem;
}

.play-button {
  position: absolute;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 2rem;
  padding: 0.8rem 1.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: bold;
  color: var(--color-primary);
}

.play-button:hover {
  background-color: white;
  transform: translateX(-50%) scale(1.05);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.play-icon {
  font-size: 1.2rem;
}

/* 剧目信息 */
.play-info {
  padding: 1.5rem;
}

.play-title {
  font-size: 1.5rem;
  margin: 0 0 0.5rem 0;
  color: var(--color-secondary);
}

.play-meta {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  color: var(--color-text-light);
  font-size: 0.9rem;
}

.play-description {
  color: var(--color-text);
  line-height: 1.6;
  margin-bottom: 1rem;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.play-tags {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  margin-bottom: 1rem;
}

.tag {
  background-color: var(--color-background-soft);
  padding: 0.3rem 0.8rem;
  border-radius: 2rem;
  font-size: 0.8rem;
  color: var(--color-text-light);
}

/* 权限提示 */
.permission-tips {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-top: 1rem;
}

.permission-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.9rem;
  color: var(--color-text-light);
}

.permission-icon {
  color: var(--color-success);
}

/* 加载更多 */
.load-more {
  text-align: center;
  margin-top: 2rem;
}

/* 推广卡片 */
.promotion-section {
  padding: 3rem 0;
}

.promotion-card {
  display: flex;
  gap: 2rem;
  background-color: var(--color-background-soft);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.promotion-image {
  flex: 1;
  min-width: 300px;
}

.promo-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.promotion-content {
  flex: 1;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.promotion-title {
  font-size: 2rem;
  margin: 0 0 1.5rem 0;
  color: var(--color-secondary);
}

.promotion-benefits {
  list-style: none;
  padding: 0;
  margin: 0 0 2rem 0;
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

.promotion-benefits li {
  font-size: 1.1rem;
  color: var(--color-text);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .banner-content {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }
  
  .plays-grid {
    grid-template-columns: 1fr;
  }
  
  .promotion-card {
    flex-direction: column;
  }
  
  .promotion-image {
    min-height: 200px;
  }
}
</style>